import React, { useState, useEffect } from "react";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import {
  Card,
  Layout,
  Tag,
  Form,
  Divider,
  Input,
  Row,
  Col,
  Avatar,
  Switch,
  Popconfirm,
  message,
  Button,
  Drawer,
  Select,
  Radio,
} from "antd";
import {
  getComponentList,
  getComponentType,
  addComponent,
  deleteComponent,
  editComponent,
  searchComponent,
  searchComponentByName,
} from "../../api/component/index";
import EditComponent from "./EditComponent/index"
import "./index.css";

const { Content } = Layout;
const { CheckableTag } = Tag;
const { Meta } = Card;

function Home() {
  const [form] = Form.useForm();
  const [componentType, setComponentType] = useState([]);
  const [componentList, setComponentList] = useState([]);
  const [, setUpdate] = useState({});
  const [visible, setVisible] = useState(false);
  // const [editVisible, setEditVisible] = useState(false);
  const [selectedTags, setSelectedTags] = useState("全部");


  //添加组件实现
  const onAddComponent = (values) => {
    console.log("onAddComponent", values);
    const componentId = String(new Date().getTime());
    const data = {
      id: componentId,
      name: values.name,
      type: values.type,
      state: {
        text: "已停止",
        value: "disabled",
      },
      creatorId: componentId,
      createTime: new Date().getTime(),
      configuration: {
        baseUrl: "http://192-168-22-65-8082.proxy.jetlinks.cn:5083/",
      },
      shareCluster: values.shareCluster,
      typeObject: {
        name: values.name,
        text: values.name,
        value: values.type,
      },
    };
    addComponent(data);
    message.success("添加成功");
    form.resetFields();
    setVisible(false);
  };

  //删除组件
  function handleDelete(id) {
    deleteComponent(id);
    setComponentList(getComponentList());
    message.success("删除成功");
  }
  //显示新增组件表单
  function showAddDrawer() {
    setVisible(true);
  }
  //关闭新增组件表单
  function onClose() {
    setVisible(false);
  }

  //按类型搜索组件
  function searchByType(type) {
    let newComponentList = searchComponent(type);
    setComponentList(newComponentList);
  }

  //按名称搜索组件
  function searchByName(name) {
    console.log(name);
    let newComponentList = searchComponentByName(name);
    setComponentList(newComponentList);
  }

  //获取更新(编辑)后的卡片信息
  const getUpdate = (id, detail) => {
    const newList = editComponent(id, detail);
    setComponentList(newList);
    setUpdate({});
  };

  function handleChange(tag, checked) {
    const nextSelectedTags = checked
      ? [tag]
      : selectedTags.filter((t) => t !== tag);
    setSelectedTags(nextSelectedTags);
  }

  useEffect(() => {
    setComponentType(getComponentType());
    setComponentList(getComponentList());
  }, []);

  //渲染组件卡片
  function renderComponent() {
    return componentList.map((component, index) => (
      <Col className="gutter-row" span={6} key={index}>
        <Card
          size="small"
          style={{ width: 300, marginTop: 16 }}
          actions={[
            <EditComponent item={component} getUpdate={getUpdate} />,
            <Popconfirm
              title="确定删除此组件吗?"
              onConfirm={() => handleDelete(component.id)}
              okText="确定"
              cancelText="取消"
            >
              <DeleteOutlined key="delete" />
            </Popconfirm>,
          ]}
        >
          <Meta
            avatar={<Avatar size="small" />}
            title={component.name}
          />
          <div className="card-body">
            <div className="card-body-type">
              <div className="card-body-type-desc">
                <span>组件类型</span>
              </div>
              <div className="card-body-type-name">
                <span>{component.type}</span>
              </div>
            </div>
            <div className="card-body-state">
              <div className="card-body-state-desc">
                <span>启动状态</span>
              </div>
              <div className="card-body-state-switch">
                <Popconfirm
                  title={
                    component.state.value === "enabled"
                      ? "确认开启"
                      : "确认停止"
                  }
                  okText="确定"
                  cancelText="取消"
                >
                  <Switch
                    size="small"
                    checked={component.state.value === "enabled"}
                    onChange={() => {
                      if (component.state.value === "enabled") {
                        component.state.value = "disabled";
                      } else {
                        component.state.value = "enabled";
                      }
                      setUpdate({});
                    }}
                  />
                </Popconfirm>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    ));
  }

  return (
    <>
      <Card>
        {/* <Breadcrumb separator=">">
          <Breadcrumb.Item href="/home">角色管理</Breadcrumb.Item>
          <Breadcrumb.Item href="/home/1">组件管理</Breadcrumb.Item>
        </Breadcrumb> */}

        <Content style={{ margin: "15px 0" }}>
          {/* 顶部搜索区域 */}
          <Form
            form={form}
            name="searchForm"
            onFinish={(values) => searchByName(values.name)}
          >
            <Form.Item name="type" label="组件类型">
              {componentType.map((tag) => (
                <CheckableTag
                  key={tag.id}
                  checked={selectedTags.indexOf(tag) > -1}
                  onChange={(checked) => handleChange(tag, checked)}
                  onClick={() => searchByType(tag.id)} //
                >
                  {tag.name}
                </CheckableTag>
              ))}
            </Form.Item>
            <Divider />
            <Form.Item name="name" label="其他选项：配置名称">
              <Input style={{ width: 300 }} />
            </Form.Item>
          </Form>
        </Content>
      </Card>
      <Row gutter={16}>
        {/* 新增卡片 */}
        <Col className="gutter-row" span={6}>
          <Card
            size="small"
            style={{
              width: 300,
              height: 161.34,
              marginTop: 16,
              textAlign: "center",
              lineHeight: 9,
            }}
          >
            <Button
              onClick={showAddDrawer}
              icon={<PlusOutlined />}
              block={true}
              style={{ border: "none", color: "rgb(155, 153, 153)" }}
            >
              新增组件
            </Button>
            <Drawer
              title="新建网络组件"
              placement="right"
              onClose={onClose}
              visible={visible}
              footer={[
                <Button onClick={onClose} style={{ marginRight: 10 }}>
                  关闭
                </Button>,
                <Button type="primary" onClick={form.submit}>
                  保存
                </Button>,
              ]}
              footerStyle={{ textAlign: "right" }}
            >
              <Form name="addForm" form={form} onFinish={onAddComponent}>
                <Form.Item
                  label="组件名称"
                  name="name"
                  rules={[{ required: true, message: "请输入组件名称" }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  label="组件类型"
                  name="type"
                  rules={[{ required: true, message: "请选择组件类型" }]}
                >
                  <Select allowClear>
                    {componentType.map((option) => (
                      <Select.Option key={option.id} value={option.id}>
                        {option.name}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item
                  label="集群"
                  name="shareCluster"
                  rules={[{ required: true, message: "请选择集群类型" }]}
                >
                  <Radio.Group style={{ marginLeft: 28 }}>
                    <Radio value={true}>共享配置</Radio>
                    <Radio value={false}>独立配置</Radio>
                  </Radio.Group>
                </Form.Item>
              </Form>
            </Drawer>
          </Card>
        </Col>
        {renderComponent()}
      </Row>
    </>
  );
}

export default Home;
